<?php
/**
 * 클라이언트 Static Files(JS,CSS)의 최적화버젼 호출
 */

include dirname(dirname(__FILE__)) . '/bootstrap.php';

$sConfpath = FW_DIR_CONF . '/conf.optimizer.php';
if (is_file($sConfpath)) {
    include $sConfpath;
}

error_reporting(0);

if (!defined('OPTIMIZER_CACHE_ROOT')) {
    define('OPTIMIZER_CACHE_ROOT', FW_DIR_CACHE);
}

/**
 * 헤더 출력
 *
 * @param $sContentType
 * @param $unique
 * @param $mtime
 * @param $size
 */
function __otmzPrintHeader($sContentType, $unique, $mtime, $size)
{
    header('Content-Type: '.$sContentType.'; charset='.FW_CHARSET);
    header('Date: '.substr(gmdate('r'), 0, -5).'GMT');
    header('Expires: '.substr(gmdate('r', strtotime('+1 MONTH')), 0, -5).'GMT');
    header('Cache-Control: private, max-age=2592000');
    header('Pragma: cache');
    header('Last-Modified: '.substr(gmdate('r', $mtime), 0, -5).'GMT');
    header('ETag: '.dechex($unique).'-'.dechex($size).'-'.dechex($mtime));
}

/**
 * Gzip 압축이 가능한지 여부
 *
 * @return boolean
 */
function __otmzIsAllowGzip()
{
    if ( preg_match('/MSIE 6.0/i',$_SERVER['HTTP_USER_AGENT']) || strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')===false || !function_exists('ob_gzhandler') ) {
        return false;
    }

    return true;
}


/**
 * 수정된 것이 있는지 여부 파악
 *
 * @param $mtime
 * @return boolean
 */
function __otmzIsNoneModified($mtime)
{
    $isCached  = false;

    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
        $time = strtotime(preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']));
        if ($mtime == $time) {
            $isCached = true;
        }
    }

    return $isCached;
}

$sHandler       = strtolower(FW_OPTIMIZER_HANDLER);
$sType          = strtolower($_GET['type']);
$sFileName      = strtolower($_GET['filename']);
$sContentType   = 'text/' . str_replace('js', 'javascript', $sType);


// 파일 타입
if ($sHandler == 'file') {

    if (preg_match('/[a-z0-9]{40}_[0-9]+/', $sFileName, $aMatch) !== 0) {
        $sRootDir = OPTIMIZER_CACHE_ROOT . DIRECTORY_SEPARATOR . $sType . DIRECTORY_SEPARATOR;
        $sFileFullPath = Optimizer::getCacheSavePath(array(
            'type' => $sHandler,
            'cache_name' =>  $aMatch[0],
            'file_root_dir' => $sRootDir
        ));
    } else {
        $sFileFullPath = utilDes::decrypt($sFileName);
    }


    $sFileFullPath = realpath($sFileFullPath);

    if (!$sFileFullPath) exit;

    $unique         = crc32($sFileFullPath);
    $mtime          = filemtime($sFileFullPath);
    $isCached       = __otmzIsNoneModified($mtime);

    if ($isCached === true) {
        header('HTTP/1.1 304');
    }

    if ( __otmzIsAllowGzip() === false ) {
        $size = filesize($sFileFullPath);
    } else {
        $f = fopen($sFileFullPath, 'r');
        $buff = fread($f, filesize($sFileFullPath));
        fclose($f);
        $buff = ob_gzhandler($buff, 5);
        $size = strlen($buff);
        header('Content-Encoding: gzip');
    }

    __otmzPrintHeader($sContentType, $unique, $mtime, $size);

    if (!$isCached) {
        if (empty($buff)) {
            $f = fopen($sFileFullPath, "r");
            fpassthru($f);
            fclose($f);
        } else {
            echo $buff;
        }
    }

// 멤캐시 타입
} else {

    if (preg_match('/[a-z0-9]{40}_([0-9]+)/', $sFileName, $aMatch) !== 0) {
        $sFileFullPath = Optimizer::getCacheSavePath(array(
            'type' => $sHandler,
            'cache_name' =>  $aMatch[0],
            'memcache_host' => FW_OPTIMIZER_MEMCACHE_HOST,
            'memcache_port' => FW_OPTIMIZER_MEMCACHE_PORT
        ));
        $mtime = $aMatch[1];
    }

    if (!$sFileFullPath) exit;

    $Memcache = new Memcache();

    $isConnect = $Memcache->connect(FW_OPTIMIZER_MEMCACHE_HOST, FW_OPTIMIZER_MEMCACHE_PORT);

    if ($isConnect === false) exit;

    $unique         = crc32($sFileFullPath);
    $sContents      = $Memcache->get($sFileFullPath);
    $isCached       = __otmzIsNoneModified($mtime);

    if ($isCached === true) {
        header('HTTP/1.1 304');
    }

    if ( __otmzIsAllowGzip() === false ) {
        $size = strlen($sContents);
    } else {
        $buff = ob_gzhandler($sContents, 5);
        $size = strlen($buff);
        header('Content-Encoding: gzip');
    }

    __otmzPrintHeader($sContentType, $unique, $mtime, $size);

    if (!$isCached) {
        if (empty($buff)) {
            echo $sContents;
        } else {
            echo $buff;
        }
    }
}